<template>
  <view class="role-list-container">
    <view class="header-section">
      <text class="page-title">角色管理</text>
    </view>
    
    <view class="toolbar-section">
      <button class="action-button" @click="showCreateRoleModal">创建角色</button>
    </view>
    
    <view class="role-list">
      <view class="role-item" v-for="role in roleList" :key="role.id">
        <view class="role-info">
          <text class="role-name">{{ role.name }}</text>
          <text class="role-description">{{ role.description }}</text>
        </view>
        <view class="role-actions">
          <button class="action-button small" @click="editRole(role)">编辑</button>
          <button class="action-button small danger" @click="deleteRole(role)">删除</button>
          <button class="action-button small" @click="assignPermissions(role)">分配权限</button>
        </view>
      </view>
    </view>
    
    <view class="empty-state" v-if="roleList.length === 0">
      <text class="empty-text">暂无角色数据</text>
    </view>
    
    <!-- 创建/编辑角色弹窗 -->
    <view class="modal" v-if="showRoleModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">{{ isEditRole ? '编辑角色' : '创建角色' }}</text>
          <button class="close-button" @click="closeRoleModal">×</button>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">角色名称</text>
            <input class="form-input" v-model="roleForm.name" placeholder="请输入角色名称" />
          </view>
          <view class="form-item">
            <text class="form-label">角色描述</text>
            <textarea class="form-textarea" v-model="roleForm.description" placeholder="请输入角色描述"></textarea>
          </view>
        </view>
        <view class="modal-footer">
          <button class="action-button cancel" @click="closeRoleModal">取消</button>
          <button class="action-button" @click="saveRole">保存</button>
        </view>
      </view>
    </view>
    
    <!-- 分配权限弹窗 -->
    <view class="modal" v-if="showPermissionModal">
      <view class="modal-content large">
        <view class="modal-header">
          <text class="modal-title">为 {{ currentRole.name }} 分配权限</text>
          <button class="close-button" @click="closePermissionModal">×</button>
        </view>
        <view class="modal-body">
          <view class="permission-list">
            <view class="permission-item" v-for="permission in allPermissions" :key="permission.id">
              <label class="permission-label">
                <checkbox 
                  :value="permission.id.toString()" 
                  :checked="selectedPermissions.includes(permission.id)"
                  @change="togglePermission(permission.id)"
                />
                <text class="permission-name">{{ permission.name }}</text>
                <text class="permission-description">{{ permission.description }}</text>
              </label>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="action-button cancel" @click="closePermissionModal">取消</button>
          <button class="action-button" @click="savePermissions">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { roleApi, permissionApi } from '../../../src/services/system'

// 定义角色类型
interface Role {
  id: number
  name: string
  description: string
}

// 定义权限类型
interface Permission {
  id: number
  name: string
  description: string
}

// 角色列表
const roleList = ref<Role[]>([])

// 是否显示角色弹窗
const showRoleModal = ref(false)

// 是否为编辑角色模式
const isEditRole = ref(false)

// 当前编辑的角色
const currentRole = ref<Role>({ id: 0, name: '', description: '' })

// 角色表单
const roleForm = ref({
  name: '',
  description: ''
})

// 是否显示权限分配弹窗
const showPermissionModal = ref(false)

// 所有权限列表
const allPermissions = ref<Permission[]>([])

// 当前角色已选择的权限
const selectedPermissions = ref<number[]>([])

// 页面加载时获取角色列表
onMounted(() => {
  fetchRoleList()
  fetchAllPermissions()
})

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response: any = await roleApi.getRoleList()
    roleList.value = response.data
    
    uni.showToast({
      title: '获取角色列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取角色列表失败:', error)
    uni.showToast({
      title: '获取角色列表失败',
      icon: 'none'
    })
  }
}

// 获取所有权限列表
const fetchAllPermissions = async () => {
  try {
    const response: any = await permissionApi.getPermissionList()
    allPermissions.value = response.data
    
    uni.showToast({
      title: '获取权限列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取权限列表失败:', error)
    uni.showToast({
      title: '获取权限列表失败',
      icon: 'none'
    })
  }
}

// 显示创建角色弹窗
const showCreateRoleModal = () => {
  isEditRole.value = false
  roleForm.value = { name: '', description: '' }
  showRoleModal.value = true
}

// 编辑角色
const editRole = (role: Role) => {
  isEditRole.value = true
  currentRole.value = { ...role }
  roleForm.value = { name: role.name, description: role.description }
  showRoleModal.value = true
}

// 删除角色
const deleteRole = async (role: Role) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除角色 "${role.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await roleApi.deleteRole(role.id)
          
          uni.showToast({
            title: '删除角色成功',
            icon: 'success'
          })
          
          // 重新获取角色列表
          fetchRoleList()
        } catch (error) {
          console.error('删除角色失败:', error)
          uni.showToast({
            title: '删除角色失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 关闭角色弹窗
const closeRoleModal = () => {
  showRoleModal.value = false
}

// 保存角色
const saveRole = async () => {
  // 表单验证
  if (!roleForm.value.name) {
    uni.showToast({
      title: '请输入角色名称',
      icon: 'none'
    })
    return
  }
  
  try {
    if (isEditRole.value && currentRole.value.id) {
      // 编辑角色
      await roleApi.updateRole(currentRole.value.id, {
        name: roleForm.value.name,
        description: roleForm.value.description
      })
      
      uni.showToast({
        title: '更新角色成功',
        icon: 'success'
      })
    } else {
      // 创建角色
      await roleApi.createRole({
        name: roleForm.value.name,
        description: roleForm.value.description
      })
      
      uni.showToast({
        title: '创建角色成功',
        icon: 'success'
      })
    }
    
    // 关闭弹窗
    closeRoleModal()
    
    // 重新获取角色列表
    fetchRoleList()
  } catch (error) {
    console.error('保存角色失败:', error)
    uni.showToast({
      title: '保存角色失败',
      icon: 'none'
    })
  }
}

// 分配权限
const assignPermissions = async (role: Role) => {
  currentRole.value = { ...role }
  showPermissionModal.value = true
  
  // 获取角色当前的权限
  try {
    const response: any = await roleApi.getRolePermissions(role.id)
    selectedPermissions.value = response.data.map((p: Permission) => p.id)
  } catch (error) {
    console.error('获取角色权限失败:', error)
    uni.showToast({
      title: '获取角色权限失败',
      icon: 'none'
    })
  }
}

// 关闭权限分配弹窗
const closePermissionModal = () => {
  showPermissionModal.value = false
}

// 切换权限选择
const togglePermission = (permissionId: number) => {
  const index = selectedPermissions.value.indexOf(permissionId)
  if (index > -1) {
    // 已选择，移除
    selectedPermissions.value.splice(index, 1)
  } else {
    // 未选择，添加
    selectedPermissions.value.push(permissionId)
  }
}

// 保存权限分配
const savePermissions = async () => {
  try {
    await roleApi.assignPermissions(currentRole.value.id, {
      permissionIds: selectedPermissions.value
    })
    
    uni.showToast({
      title: '权限分配成功',
      icon: 'success'
    })
    
    // 关闭弹窗
    closePermissionModal()
  } catch (error) {
    console.error('权限分配失败:', error)
    uni.showToast({
      title: '权限分配失败',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.role-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.toolbar-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  text-align: right;
}

.action-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 15rpx 30rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  
  &.small {
    padding: 10rpx 20rpx;
    font-size: 24rpx;
  }
  
  &.danger {
    background-color: #f44336;
  }
  
  &.cancel {
    background-color: #999;
  }
}

.role-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.role-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.role-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.role-description {
  font-size: 28rpx;
  color: #666;
}

.role-actions {
  display: flex;
  gap: 10rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 10rpx;
  width: 90%;
  max-width: 600rpx;
  
  &.large {
    max-width: 800rpx;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
  padding: 0;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.form-input {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  box-sizing: border-box;
}

.form-textarea {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  height: 150rpx;
  box-sizing: border-box;
}

.permission-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.permission-item {
  padding: 20rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.permission-label {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.permission-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.permission-description {
  font-size: 24rpx;
  color: #666;
  margin-top: 5rpx;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 2rpx solid #f5f5f5;
}
</style>